package org.apache.servicecomb.samples.practise.houserush.gateway.filter;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.servicecomb.common.rest.codec.produce.ProduceProcessor;

import javax.ws.rs.core.MediaType;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;

/**
 * @Author: Snake Man
 * @system: 解决dispatcher时间错误，解析时间
 * @DateTime: 2022/1/9 17:51
 * @Description:
 */
public class ProduceJsonProcessor implements ProduceProcessor {

    private ObjectMapper mapper = new ObjectMapper();

    public ProduceJsonProcessor() {
        //原生的设置
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
        );
        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        mapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)
        ;
        mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
        //解决时间转换问题，设置时间格式
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        mapper.setDateFormat(format);
        //数据为空处理
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    @Override
    public String getName() {
        return MediaType.APPLICATION_JSON;
    }

    @Override
    public void doEncodeResponse(OutputStream output, Object
            result) throws Exception {
        mapper.writeValue(output, result);
    }

    @Override
    public Object doDecodeResponse(InputStream input, JavaType
            type) throws Exception {
        return mapper.readValue(input, type);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}


